#!/usr/bin/env python
# coding=utf-8
from __future__ import absolute_import
import os
import tornado.web
from tornado.options import define

import WorkManager
import WrapCursor
from TimingSwitch import *
from database.DataBaseHelper import InitDatabase
from database.models.DatabaseCommon import engine
from global_status import ai_ele_global_config
from handlers.MasterInfo.GetMasterInfo import GetMasterInfoHandler
from handlers.MasterInfo.ResetMaster import ResetMasterInfoHandler
from handlers.MasterInfo.SetMasterInfo import SetMasterInfoHandler
from handlers.PanelManage.GetPanelNormal import GetPanelNormal
from handlers.Timing.AddTiming import AddTimingSwitch
from handlers.Timing.DelTIming import DelTimingSwitch
from handlers.Timing.GetTiming import GetTimingSwitch
from handlers.Timing.ModTimingName import ModTimingSwitchNameHandler
from handlers.Timing.SetTiming import SetTimingSwitch
from handlers.Timing.UptTiming import UpdTimingSwitch
from handlers.controller_manager.GetControllerInfo import GetDeviceInfoHandler
from handlers.controller_manager.delete_controller import DelDeviceHandler
from handlers.controller_manager.get_unnamed_controller import NewDeviceHandler
from handlers.controller_manager.insert_controller import InsDeviceHandler
from handlers.controller_manager.name_new_device import NameNewDeviceHandler
from handlers.index import IndexHandler
from handlers.normal_manager.AddNormalSteps import InsNormalStepHandler
from handlers.normal_manager.DelAdvNormal import DelAdvanceFlowHandler
from handlers.normal_manager.DelNormal import DelNormalFlowHandler
from handlers.normal_manager.GetAdvNormal import GetAdvanceFlowHandler
from handlers.normal_manager.GetAdvNormalSteps import GetAdvNormalStepHandler
from handlers.normal_manager.GetNormal import GetNormalFlowHandler
from handlers.normal_manager.GetNormalSteps import GetNormalStepHandler
from handlers.normal_manager.InsAdvNormal import InsAdvanceFlowHandler
from handlers.normal_manager.InsNormal import InsNormalFlowHandler
from handlers.normal_manager.ModNormalName import ModNormalNameHandler
from handlers.normal_manager.UptAdvNormalSteps import UptAdvNormalStepHandler
from handlers.normal_manager.UptNormalSteps import UptNormalStepHandler
from handlers.point_manager.GetNewPoint import GetNewControlPointsHandler
from handlers.point_manager.GetPointInfo import GetControlPointInfoHandler
from handlers.point_manager.NamedPoint import NameNewControlPointsHandler
from handlers.point_manager.SetSinglePoint import SetSinglePoint
from test_script.test_insert_controller import InsDeviceHandlerTest
from handlers.PanelManage.AddPanelNormal import AddPanelNormal
from handlers.PanelManage.UptPanelNormal import UptPanelNormal
from handlers.PanelManage.DelPanelNormal import DelPanelNormal

define("port", default=6000, help="run on the given port", type=int)


class StartWorkHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            desc = ojson['id']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error('request data error:' + str(e.message)))
            return
        iid = ojson['id']
        CheckT = global_status.ai_ele_global_status.Get4NormalMap(str(iid))
        if CheckT is None or len(CheckT) != 0:
            logger.debug('CheckT not ok:',CheckT,' len is:',len(CheckT));
            self.write(r.Error(u'模式已在运行'))
            return
        engine.dispose()
        awork = WorkManager(iid)
        is_ok = awork.CheckError()
        if is_ok['code'] is not 0:
            logging.warn("thread work check is not ok")
            self.write(json.dumps(is_ok))
            return
        awork.Start()
        self.write(r.Ok('start work ok'))
        return


if __name__ == "__main__":
    tornado.options.parse_command_line()
    logger = logging.getLogger('tornado')
    logger.setLevel(logging.DEBUG)
    import os
    fileHandler = logging.FileHandler(os.getcwd()+"/api-server.log")
    fileHandler.setLevel(logging.DEBUG)
    fileFormatter = logging.Formatter('[%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s')
    fileHandler.setFormatter(fileFormatter)
    logging.root.addHandler(fileHandler)
    logging.root.setLevel(logging.DEBUG)
    logging.info("application start")
    tornado.log.enable_pretty_logging(logger=logger)
    logging.info('ai-ele application start')
    t = TimingSwitchThread()
    t.start()
    InitDatabase()
    app = tornado.web.Application(
        handlers=[
            (r"/", IndexHandler),
            # 主机信息
            (r"/set_master_info", SetMasterInfoHandler),  # 主机设置
            (r"/reset_master_info", ResetMasterInfoHandler),
            (r"/get_master_info", GetMasterInfoHandler),
            # 从机管理
            (r"/ins_new_device", InsDeviceHandler),  # 插入新的机板注册地址
            (r"/ins_new_device_test", InsDeviceHandlerTest),  # 插入新的丛机板进行测试
            (r"/get_new_devices", NewDeviceHandler),
            (r"/name_new_device", NameNewDeviceHandler),  # 命名从机
            (r"/del_device", DelDeviceHandler),  # 删除从机
            (r"/get_device_info", GetDeviceInfoHandler),
            # 控制点管理
            (r"/get_new_controlpoints", GetNewControlPointsHandler),
            (r"/name_new_controlpoints", NameNewControlPointsHandler),
            (r"/get_controlpoint_info", GetControlPointInfoHandler),
            (r"/set_single_point", SetSinglePoint),
            # 模式管理
            (r"/ins_normal_flow", InsNormalFlowHandler),  # 插入常规模式
            (r"/get_normal_flow", GetNormalFlowHandler),  # 查询常规模式
            (r"/del_normal_flow", DelNormalFlowHandler),  # 删除模式
            (r"/ins_normal_step", InsNormalStepHandler),  # 增加常规模式动作
            (r"/get_normal_step", GetNormalStepHandler),  # 查询常规模式动作
            (r"/mod_normal_name", ModNormalNameHandler),  # 修改常规模式名字
            # 高级模式
            (r"/ins_advance_flow", InsAdvanceFlowHandler),
            (r"/get_advance_flow", GetAdvanceFlowHandler),
            (r"/del_advance_flow", DelAdvanceFlowHandler),
            (r"/upt_flow_opts", UptNormalStepHandler),
            (r"/upt_adv_flow_opts", UptAdvNormalStepHandler),  # 更新高级模式动作
            (r"/get_adv_normal_steps", GetAdvNormalStepHandler),  # 更新高级模式动作
            # 开启任务
            (r"/start_work", StartWorkHandler),
            # 定时管理
            (r"/add_timing_switch", AddTimingSwitch),  # 增加定时模式
            (r"/upd_timing_switch", UpdTimingSwitch),  # 更新定时模式
            (r"/get_timing_switch", GetTimingSwitch),  # 查询定时操作
            (r"/del_timing_switch", DelTimingSwitch),  # 删除定时模式
            (r"/set_timing_switch", SetTimingSwitch),  # 设置定时模式
            (r"/mod_timing_switch_name", ModTimingSwitchNameHandler),  # 设置定时模式名字
            # 按键板设置
            (r"/add_panel_normal", AddPanelNormal),  # 增加按键功能
            (r"/upd_panel_normal", UptPanelNormal),  # 更新按键功能
            (r"/del_panel_normal", DelPanelNormal),  # 删除按键功能
            (r"/get_panel_normal", GetPanelNormal),  # 查询按键功能

        ],
        autoreload=False,
        debug=False
    )

    if ai_ele_global_config['useHttps']:
        https_server = tornado.httpserver.HTTPServer(app, ssl_options={
            "certfile": os.path.join(os.path.abspath("."), 'openssl-keys', "server.crt"),
            "keyfile": os.path.join(os.path.abspath("."), 'openssl-keys', "server.key"),
        })
        https_server.listen(16000)
    else:
        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(16000)
    tornado.ioloop.IOLoop.instance().start()
    cur.close()
    con.close()
